<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\model;

use think\Model;

class File extends Model
{
    // 搜索器
    public function searchKeywordAttr($query, $value, $array)
    {
    	if (! empty($value)) {
	        $query->where("title",'like', '%' . $value . '%');
            $query->where("folder", 0);
	    }
    }

    public function searchTypeAttr($query, $value, $array)
    {
        if ($array['type'] !== 'recycle') {
            $query->where("type", $value);
        }
    }

    public function searchPidAttr($query, $value, $array)
    {
        if ($array['type'] === 'recycle' || $array['keyword'] !== '') {
            return;
        } else {
            $query->where("pid", $value);
        }
    }

    public function searchStatusAttr($query, $value, $array)
    {
        $query->where("status", $value);
    }

    // 递归删除
    public static function recursiveDestroy($ids) {
        $url = self::whereIn('id', $ids)->column('url');
        foreach ($url as $key => $name) {
            $file  = app()->getRootPath() . 'public' . $name;
            $arr   = explode('.', $file);
            if (count($arr) > 1) {
                $cover = $arr[0] . '40x40.' . $arr[1];
                if(is_file($file)) unlink($file);
                if(is_file($cover)) unlink($cover);
            }
        }
        self::destroy($ids);
        $ids = self::whereIn('pid', $ids)->column('id');
        if ($ids) {
            self::recursiveDestroy($ids);
        }
    }

    // 递归计算
    public static function countSizeFolder($ids) {
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        $where[] = ['pid', 'in', $ids];
        $where[] = ['status', '=', 1];
        $newSize = 0;
        $nowSize = self::where($where)->sum('size');
        $ids     = self::where($where)->column('id');
        if ($ids) {
            $newSize = self::countSizeFolder($ids);
        }
        $size = $newSize + $nowSize;
        return $size;
    }
}